/*
 *  Class name: AccountPropertyEditor.java
 *  Version: 1.0
 *  Date: 23.6.2014
 */

package cz.morosystems.personwebmanager.presentationlayer.propertyeditors;

import cz.morosystems.personwebmanager.businesslayer.sevices.AccountService;
import cz.morosystems.personwebmanager.persistencelayer.entities.Account;
import java.beans.PropertyEditorSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *
 * @author Michal Ďuriš
 */
@Component
public class AccountPropertyEditor extends PropertyEditorSupport {

    @Autowired
    private AccountService accountService;

    public AccountPropertyEditor() {
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        
        if(text == null || text.isEmpty()) {
            setValue(null);
        }
        
        try {
            
            Long id = Long.valueOf(text);
            setValue(accountService.getAccountByID(id));
            
        }catch(NumberFormatException ex) {
            setValue(null);
        }
    }

    @Override
    public String getAsText() {
        
        if(getValue() == null) {
            return "";
        }
        
        return Long.toString(((Account) getValue()).getId());
    }
    
    
    
}
